package com.emin.platform.subjectcenter.service.impl;

import com.emin.base.dao.PageRequest;
import com.emin.base.dao.PagedResult;
import com.emin.base.dao.PreFilter;
import com.emin.base.dao.PreFilters;
import com.emin.base.exception.EminException;
import com.emin.base.service.UndeleteableServiceImpl;
import com.emin.base.util.CommonsUtil;
import com.emin.platform.subjectcenter.common.constant.ECMStatus;
import com.emin.platform.subjectcenter.common.response.ResponseBack;
import com.emin.platform.subjectcenter.entity.Ecm;
import com.emin.platform.subjectcenter.entity.Industory;
import com.emin.platform.subjectcenter.feign.ChainService;
import com.emin.platform.subjectcenter.service.ECMService;
import com.emin.platform.subjectcenter.service.IndustoryService;
import com.emin.platform.subjectcenter.vo.EcmRequestVo;
import com.emin.platform.subjectcenter.vo.EcmResponseVo;
import com.emin.platform.subjectcenter.vo.PageResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

import static com.emin.platform.subjectcenter.common.constant.ECMStatus.ACTIVATE_FLAG;
import static com.emin.platform.subjectcenter.common.constant.ECMStatus.DISABLE_FLAG;
import static com.emin.platform.subjectcenter.entity.Ecm.*;
import static com.emin.platform.subjectcenter.exception.ExceptionCode.*;


/**
 * 主体中心服务类
 *
 * @author Jack
 * @version V1.0
 * @Title:
 * @Description: 主体中心服务类
 * @date 2017/10/25 11:47
 */
@Service
public class ECMServiceImpl extends UndeleteableServiceImpl<Ecm> implements ECMService {


    @Autowired
    private IndustoryService industoryService;

    @Autowired
    private ChainService chainService;


    @Override
    public ResponseBack<Boolean> save(EcmRequestVo vo) {
        try {
            final Long id = vo.getId();
            Ecm checkEcm = null;
            int activeStatus = 0;
            if (null != id) {
                // 修改
                PreFilter idFilter = PreFilters.eq(ECM_ID, vo.getId());
                checkEcm = this.findUniqueByPreFilter(idFilter, getStatusFilter());
                if (null == checkEcm) {
                    throw new EminException(ECM_ID_ERROR.getCode());
                }
                activeStatus = checkEcm.getActiveStatus();
                if (this.isDisable(activeStatus)) {
                    throw new EminException(ECM_IS_DISABLE_ERROR.getCode());

                }
            }
            // 校验名称是否重复
            String name = vo.getName();
            if (!StringUtils.isBlank(name)) {
                if (this.checkNameIsRepeat(id, name)) {
                    throw new EminException(ECM_NAME_IS_REPEAT.getCode());
                }
            }
            // vo转换成entity
            Ecm ecm = vo.convert(this.isActivate(activeStatus), checkEcm);
            String industorieIds = vo.getIndustryIds();
            if (!StringUtils.isBlank(industorieIds)) {
                Long[] industors = CommonsUtil.stringToLongArr(industorieIds);
                List<Industory> ecmIndustories = new ArrayList<>();
                if (null != industors && industors.length > 0) {
                    // 查询主体行业
                    ecmIndustories = industoryService.findByIds(industors);
                }
                ecm.setIndustories(ecmIndustories);
            }
            this.saveOrUpdate(ecm);
//            if (id == null) {
//                chainService.createChain(ecm.getId());
//            } else {
//                throw new EminException(ECM_CREATE_CHAIN_ERROR.getCode());
//            }
            return ResponseBack.success(true);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 校验name是否重复
     *
     * @param id   主体ID
     * @param name 主体名称
     * @return boolean
     * @throws
     * @Description: true：重复;false:未重复
     * @author Jack
     * @date 2017/10/25
     */
    private boolean checkNameIsRepeat(Long id, String name) {
        PreFilter nameFilter = PreFilters.eq(ECM_NAME, name);
        Ecm ecm = this.findUniqueByPreFilter(nameFilter);
        if (null != id && id.compareTo(ecm.getId()) == 0) {
            ecm = null;
        }
        return ecm == null ? false : true;
    }

    @Override
    public ResponseBack<PageResponse<EcmResponseVo>> queryPage(PageRequest request, Long
            industryId, String keyword) {
        try {
            PreFilter matchFilter = null;
            PreFilter ecmIndustoryFilter = null;
            if (null != industryId) {
                ecmIndustoryFilter = PreFilters.eq(Ecm.PROP_INDUSTORY_ID, industryId);
            }
            if (!StringUtils.isBlank(keyword)) {
                PreFilter[] filters = new PreFilter[2];
                filters[0] = PreFilters.like(ECM_NAME, keyword);
                filters[1] = PreFilters.like(ECM_SN, keyword);
                matchFilter = PreFilters.or(filters);
            }
            PagedResult<Ecm> pagedResult = this.getPage(request, ecmIndustoryFilter, matchFilter);
            PageResponse<EcmResponseVo> result = this.convertPageResult(request, pagedResult);
            return ResponseBack.success(result);
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    public ResponseBack<EcmResponseVo> queryDetail(Long id) {
        try {
            PreFilter idFilter = PreFilters.eq(ECM_ID, id);
            Ecm ecm = this.findUniqueByPreFilter(idFilter);
            EcmResponseVo vo = new EcmResponseVo();
            vo.convert(ecm);
            return ResponseBack.success(vo);
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    @Transactional
    public ResponseBack<Boolean> activate(String ids) {
        return this.updateStatus(ids, ACTIVATE_FLAG);
    }

    @Override
    @Transactional
    public ResponseBack<Boolean> disable(String ids) {
        return this.updateStatus(ids, DISABLE_FLAG);
    }

    private ResponseBack<Boolean> updateStatus(String ids, ECMStatus type) {
        try {
            Long[] longIds = CommonsUtil.stringToLongArr(ids);
            for (Long id : longIds) {
                PreFilter idFilter = PreFilters.eq(ECM_ID, id);
                Ecm ecm = this.findUniqueByPreFilter(idFilter);
                ecm.setActiveStatus(type.getCode());
                this.update(ecm);
            }
            return ResponseBack.success(true);
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    public ResponseBack<List<EcmResponseVo>> findByKeyword(String keyword) {
        try {
            PreFilter[] filters = new PreFilter[2];
            filters[0] = PreFilters.like(ECM_NAME, keyword);
            filters[1] = PreFilters.like(ECM_SN, keyword);
            PreFilter matchFilter = PreFilters.or(filters);
            List<Ecm> queryResult = this.findByPreFilter(matchFilter);
            List<EcmResponseVo> result = this.convertQueryResult(queryResult);
            return ResponseBack.success(result);
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    public ResponseBack<Boolean> checkIsActivate(Long id) {
        try {
            PreFilter idFilter = PreFilters.eq(ECM_ID, id);
            Ecm ecm = this.findUniqueByPreFilter(idFilter);
            return ResponseBack.success(isActivate(ecm.getActiveStatus()));
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    private List<EcmResponseVo> convertQueryResult(List<Ecm> queryResult) {
        List<EcmResponseVo> resultList = null;
        if (null != queryResult && queryResult.size() > 0) {
            resultList = new ArrayList<EcmResponseVo>();
            for (Ecm ecm : queryResult) {
                EcmResponseVo vo = new EcmResponseVo();
                resultList.add(vo.convert(ecm));
            }
        }
        return resultList;
    }


    /**
     * @param request
     * @param pagedResult 分页请求信息
     * @return PagedResult<EcmResponseVo>
     * @throws
     * @Description: 将实体类转换成vo
     * @author Jack
     * @date 2017/10/25
     */
    private PageResponse<EcmResponseVo> convertPageResult(PageRequest request, PagedResult<Ecm>
            pagedResult) {
        if (null != pagedResult) {
            List<EcmResponseVo> resultList = null;
            List<Ecm> queryResult = pagedResult.getResultList();
            resultList = this.convertQueryResult(queryResult);
            return new PageResponse<EcmResponseVo>(resultList, pagedResult.getNextOffset(),
                    pagedResult.getTotalCount(), request.getCurrentPage(), pagedResult
                    .getTotalPageNum());
        }
        return null;
    }

    public Boolean isActivate(int activeStatus) {
        return activeStatus == ACTIVATE_FLAG.getCode();
    }

    public Boolean isDisable(int activeStatus) {
        return activeStatus == DISABLE_FLAG.getCode();
    }
}
